package com.numberone.master.modules.Interfaces.web;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.numberone.master.modules.recharge.entity.Package;
import com.numberone.master.modules.recharge.service.PackageService;
import com.numberone.master.modules.rsa.service.RsaService;
import com.numberone.master.modules.sys.dao.OfficeCardDao;
import com.numberone.master.modules.sys.entity.OfficeCard;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.google.gson.JsonObject;
import com.numberone.master.common.Interface.YiDong;
import com.numberone.master.common.exception.BizException;
import com.numberone.master.common.exception.RespResult;
import com.numberone.master.common.menu.RespCode;
import com.numberone.master.common.utils.JsonUtils;
import com.numberone.master.common.utils.StringUtils;
import com.numberone.master.common.wxpay.Encrypt;
import com.numberone.master.common.wxpay.Example;
import com.numberone.master.modules.Interfaces.service.WLWKService;
import com.numberone.master.modules.card.entity.Card;
import com.numberone.master.modules.card.entity.CardAmount;
import com.numberone.master.modules.card.entity.CardRechargeFlow;
import com.numberone.master.modules.card.service.CardAmountService;
import com.numberone.master.modules.card.service.CardService;
import com.numberone.master.modules.orders.entity.RechargeOrder;
import com.numberone.master.modules.orders.service.RechargeOrderService;

/**
 * 接口Controller
 * @author chengkang
 * @version 2018-01-23
 */
@Controller
@RequestMapping(value = "${adminPath}/wlwk")
public class WLWKController {
	
	@Autowired
	private WLWKService WLWKService;
	@Autowired
	private CardService cardService;
	@Autowired
	private PackageService packageService;
	@Autowired
	private OfficeCardDao officeCardDao;
	@Autowired
	RechargeOrderService rechargeOrderService;
	@Autowired
	private RsaService rsaService;
	@Autowired
	private CardAmountService cardAmountService;
	
	public static final String MONEY = "^(([1-9]{1}\\d*)|([0]{1}))(\\.(\\d){0,2})?$";
	
	/**
	 * 根据iccid查询套餐信息
	 * @param iccid
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "user/taocanQuery")
	@ResponseBody
	public RespResult taocanQuery(@RequestParam(value = "iccid", required = false)String iccid
			,HttpServletRequest request) {
		List<Package> list = WLWKService.packList(iccid);
		return RespResult.getInstance(RespCode.SUCCESS,list);
	}
	
	/**
	 * 添加充值预订单
	 * @param lsno 订单号
	 * @param tctype 套餐类型
	 * @param tc_id 套餐id
	 * @param money 价格
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "user/encode/orderInsert",method = RequestMethod.POST)
	@ResponseBody
	public RespResult orderInsert(HttpServletRequest request) {
		try {
			String lsno = request.getParameter("lsno");
			String tc_id = request.getParameter("tc_id");
			String money = request.getParameter("money");
			String iccid = request.getParameter("iccid");
			//查询所属用户
//			User user = systemService.getUserByLoginName(account);
//			RsaKey rasKey = rsaService.selectRsaKey(user.getId());
//			//RSA解密
//			byte[] rsaRes = RSAUtils.decryptByPublicKey(BASE64.decodeBASE64(encoded), rasKey.getPublicKey());
//			//json解析
//			Map<String,Object> msgMap = JsonUtils.fromJson(new String(rsaRes));
//			String lsno = (String)msgMap.get("lsno");
//			String tc_id = (String)msgMap.get("tc_id");
//			String money = (String)msgMap.get("money");
//			String iccid = (String)msgMap.get("iccid");
			if(StringUtils.isBlank(lsno) ||  StringUtils.isBlank(tc_id) || StringUtils.isBlank(money) || StringUtils.isBlank(iccid)){
				throw new BizException(RespCode.NOT_PARAM_ERROR);
			}
			if(!money.matches(MONEY)){
				throw new BizException(RespCode.MONEY_FORMAT_ERROR);
			}
			//查询卡
			Card card = cardService.getCardInfoByCCID(iccid);
			if(card == null){
				throw new BizException("-1","iccid不存在。");
			}
			//查询卡的所属人
			OfficeCard officeCard = officeCardDao.selectThePeople(card.getId());
			if(officeCard == null){
				throw new BizException("-1","未查询到卡的所属代理商。");
			}
			//查询订单信息
			RechargeOrder r = rechargeOrderService.findRechargeLsByLsno(lsno);
			if(r != null){
				throw new BizException("-1","订单号已经存在。");
			}
			Double prices = new Double(money);
			if(Double.doubleToLongBits(prices) < Double.doubleToLongBits(0)){
				throw new BizException("-1","充值金额不得小于0元。");
			}
			Package p = packageService.isPackageCount(officeCard.getOfficeId(), tc_id);
			if(p == null){
				throw new BizException("-1","此代理商还未持有此套餐。");
			}
			Double moneyPrice = new Double(money);//主套餐销售价格
			BigDecimal data1 = new BigDecimal(moneyPrice);
			BigDecimal data2 = new BigDecimal(p.getSalePrice());
			if(data1.compareTo(data2) == -1){
				throw new BizException("-1","充值金额不得低于套餐定价金额。");
			}
			RechargeOrder rechargeLs = new RechargeOrder();
			rechargeLs.setOfficeId(officeCard.getOfficeId());
			rechargeLs.setOrderNo(lsno);
			rechargeLs.setPkg(p.getType());
			rechargeLs.setMoney(money);
			rechargeLs.setIccid(iccid);
			rechargeLs.setCreateDate(new Date());
			rechargeLs.setCreateById("1");
			rechargeLs.setDelFlag("0");
			rechargeLs.setPayState("1");
			rechargeLs.setRechargeState("1");
			rechargeLs.setPkgType(tc_id);
			rechargeLs.setRemarks("充值");
			rechargeOrderService.insert(rechargeLs);
		} catch (Exception e) {
			throw new BizException("-1",e.getMessage());
		}
		return RespResult.getInstance(RespCode.SUCCESS);
	}
	
	/**
	 * 修改订单
	 * @param lsno 订单号
	 * @return
	 */
	@RequestMapping(value = "user/encode/orderUpdate",method = RequestMethod.POST)
	@ResponseBody
	public RespResult orderUpdate(HttpServletRequest request) {
		try {
			String lsno = request.getParameter("lsno");
			/*//查询所属用户
			User user = systemService.getUserByLoginName(account);
			RsaKey rasKey = rsaService.selectRsaKey(user.getId());
			//RSA解密
			byte[] rsaRes = RSAUtils.decryptByPublicKey(BASE64.decodeBASE64(encoded), rasKey.getPublicKey());
			//json解析
			Map<String,Object> msgMap = JsonUtils.fromJson(new String(rsaRes));
			String lsno = (String)msgMap.get("lsno");*/
			if(StringUtils.isBlank(lsno)){
				throw new BizException(RespCode.NOT_PARAM_ERROR);
			}
			//查询是否存在此订单
			RechargeOrder r = rechargeOrderService.findRechargeLsByLsno(lsno);
			if(r == null){
				throw new BizException("-1","订单号不存在。");
			}
			if(StringUtils.equals(r.getPayState(), "2")){
				throw new BizException("-1","此订单号已经支付。");
			}
			if(!StringUtils.equals(r.getRechargeState(), "1")){
				throw new BizException("-1","此订单已经审核。");
			}
			r.setPayState("2");
			r.setRechargeTime(new Date());
			rechargeOrderService.update(r);
		} catch (Exception e) {
			throw new BizException("-1",e.getMessage());
		}
		return RespResult.getInstance(RespCode.SUCCESS);
	}
	
	/**
	 * 根据iccid查询套餐
	 * @param iccid
	 * @return
	 */
	@RequestMapping(value = {"user/getInfosByIccid", ""})
	@ResponseBody
	public RespResult getInfosByIccid(@RequestParam(value = "iccid", required = false)String iccid) {
		Map<String,Object> map = WLWKService.getInfosByIccid(iccid);
		return RespResult.getInstance(RespCode.SUCCESS,map);
	}
	
	/**
	 * 查询卡余额
	 * @param iccid
	 * @return
	 */
	@RequestMapping(value = {"user/findYuEByICCID", ""})
	@ResponseBody
	public RespResult findYuEByICCID(@RequestParam(value = "iccid", required = false)String iccid) {
		String res = WLWKService.findYuEByICCID(iccid);
		return RespResult.getInstance(RespCode.SUCCESS,res);
	}
	
	/**
	 * 支付回调
	 * @param request
	 * @return
	 */
	@RequestMapping(value = {"resultNotification", ""})
	@ResponseBody
	public Map<String,Object> findYuEByICCID(HttpServletRequest request) {
		Map<String,Object> map = WLWKService.update(request);
		return map;
	}
	
	
	/**
	 * 物联网卡支付操作
	 * @param openId 微信影虎openId
	 * @param money 支付金额
	 * @param lsno 订单号
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value ="/wxpay", method = RequestMethod.POST)
	@ResponseBody
    public RespResult order(@RequestParam String openId,@RequestParam String money,@RequestParam String lsno) throws Exception{
		if(StringUtils.isBlank(openId) || StringUtils.isBlank(money) || StringUtils.isBlank(lsno)){
			throw new BizException(RespCode.NOT_PARAM_ERROR);
		}
		//查询是否存在此订单
		RechargeOrder r = rechargeOrderService.findRechargeLsByLsno(lsno);
		if(r == null){
			throw new BizException("-1","订单号不存在。");
		}
		if(StringUtils.equals(r.getPayState(), "2")){
			throw new BizException("-1","此订单号已经支付。");
		}
		if(!StringUtils.equals(r.getRechargeState(), "1")){
			throw new BizException("-1","此订单已经审核。");
		}
		Double moneyPrice = new Double(money);//主套餐销售价格
		BigDecimal data1 = new BigDecimal(moneyPrice);
		BigDecimal data2 = new BigDecimal(r.getMoney());
		if(data1.compareTo(data2) != 0){
			throw new BizException("-1","支付金额和订单金额不一致。");
		}
        Example example = new Example();
        JsonObject jsonObject = new JsonObject();
        jsonObject.addProperty("merchantid",Example.cooperator);

//        交易金额    srcAmt  Double  Y   单位圆，精确到分,如1.23
        jsonObject.addProperty("srcAmt",money);
        jsonObject.addProperty("bizOrderNumber",lsno);
//        支付类型    walletType  Varchar(32) Y   1,支付宝.2, 微信
        jsonObject.addProperty("walletType",2);
//        异步通知地址  notifyUrl   Varchar(128)    Y   以http 或https 开头，商户用于接收异步通知的地址
        jsonObject.addProperty("notifyUrl",Example.NO_TIFY_URL);
        jsonObject.addProperty("subOpenId",openId);//微信用户id
        jsonObject.addProperty("subAppId",Example.WX_APP_ID);
        jsonObject.addProperty("goods_desc","物联网卡充值");
        String response = example.make_request(jsonObject,Example.PAYMENTH5,"SZZF008");
        String ss = example.parse_response(response);
        JSONObject js = JSONObject.parseObject(ss); 
        String sss = js.getString("sdkParam");
        JSONObject sdkParam = JSONObject.parseObject(sss);
		String res = sdkParam.toString();
        return RespResult.getInstance(RespCode.SUCCESS,res);
    }
	/**
	 * 
	 * @param merchantid
	 * @param bizOrderNumber
	 * @param srcAmt
	 * @param walletSerialNumber
	 * @param txnStatus
	 * @return
	 */
	@RequestMapping(value ="/notifyOrder", method = RequestMethod.POST)
    public String notifyOrder(HttpServletRequest request){
		System.out.println("==================进入茗语付通代付返回通知====================");
		StringBuilder sb = new StringBuilder();
        try {
        	// 读取请求内容  
            BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream(),"utf-8"));  
            String line = null;  
			while ((line = br.readLine()) != null) {  
			    sb.append(line);  
			}
		} catch (IOException e) {
			e.printStackTrace();
		}  
        //将json字符串转换为json对象  
        JSONObject json = JSONObject.parseObject(sb.toString());
        System.out.println("==================茗语付通代付回调数据格式=====================");
        //String encryptData = Encrypt.aesEncrypt(sb.toString(),Example.aesKey);
        System.out.println(json);
        Map<String,Object> msgMap = JsonUtils.fromJson(json.toString());
        String txnStatus = (String)msgMap.get("txnStatus");
        String bizOrderNumber = (String)msgMap.get("bizOrderNumber");
		
        //JSONObject encryptDataObj = JSONObject.parseObject(encryptData);
        //订单状态
        //String txnStatus = encryptDataObj.getString("txnStatus");
        //订单号
        //String bizOrderNumber = encryptDataObj.getString("bizOrderNumber");
        System.out.println("==================茗语付通代付回调订单状态====================="+txnStatus);
        System.out.println("==================茗语付通代付回调订单号====================="+bizOrderNumber);
		//查询是否存在此订单
		RechargeOrder r = rechargeOrderService.findRechargeLsByLsno(bizOrderNumber);
		if(r == null){
			//没有次订单，添加一个未知订单，做为以后订单对账
			return "SUCCESS";
		}else{
			System.out.println("==================茗语付通代付回调订单状态====================="+txnStatus);
			if(StringUtils.equals(txnStatus, "s")){
				r.setPayState("2");
				r.setRechargeTime(new Date());
				rechargeOrderService.update(r);
				return "SUCCESS";
			}else{
				r.setPayState("1");
				r.setRechargeTime(new Date());
				rechargeOrderService.update(r);
				return "SUCCESS";
			}
		}
	}
	
	/**
	 * 查询卡的实时流量和状态
	 * @param iccid 卡的iccid
	 * @param type  类型
	 * @param EBID
	 * @param request
	 * @return
	 * @throws JsonProcessingException 
	 */
	@RequestMapping(value = {"user/selectCardFlow", ""})
	@ResponseBody
	public RespResult selectCardFlow(@RequestParam(value = "iccid", required = false)String iccid,
			@RequestParam(value = "areaId", required = false)String areaId,
			@RequestParam(value = "ebid", required = false)String ebid,
			HttpServletRequest request) throws JsonProcessingException {
		if(StringUtils.equals(areaId, "5")){
		 	String res = cardService.getCardInfo(iccid, ebid);
		 	if(StringUtils.isBlank(res)){
		 		return RespResult.getInstance("-1","接口调用失败");
		 	}
		 	Map<String,Object> msgMap = JsonUtils.fromJson(res);
			String status = (String)msgMap.get("status");
			if(StringUtils.equals(status, "0")){
				return RespResult.getInstance(RespCode.SUCCESS,res.replaceAll("status","STATUS"));
			}else{
				return RespResult.getInstance("-1","查询失败");
			}
		}else{
			String transid = rsaService.getTransid();
		 	String res  = YiDong.yiDongPost(ebid, areaId, iccid, transid);
		 	if(StringUtils.isBlank(res)){
		 		return RespResult.getInstance("-1","接口调用失败");
		 	}
		 	Map<String,Object> msgMap = JsonUtils.fromJson(res);
			String status = (String) msgMap.get("status");
			if(StringUtils.equals(status, "0")){
				return RespResult.getInstance(RespCode.SUCCESS,res);
			}else{
				return RespResult.getInstance("-1","查询失败");
			}
		}
	}
	
	/**
	 * 根据iccid得到首页信息
	 * @param iccid
	 * @return
	 */
	@RequestMapping(value = "mpos/getMposIndex")
	@ResponseBody
	public RespResult getMposIndex(@RequestParam(value = "iccid", required = false)String iccid) {		
		Map<String,Object> map = WLWKService.getMposIndex(iccid);
		return RespResult.getInstance(RespCode.SUCCESS,map);
	}
	
	/**
	 * 根据iccid查询卡的详情
	 * @param iccid
	 * @return
	 */
	@RequestMapping(value = "mpos/getIccidInfo")
	@ResponseBody
	public RespResult getIccidInfo(@RequestParam(value = "iccid", required = false)String iccid) {
		//查询卡
		if(StringUtils.isBlank(iccid)){
			throw new BizException(RespCode.NOT_PARAM_ERROR);
		}
		Card card = cardService.getCardByCCID(iccid, "0");
		if(card == null){
			throw new BizException("9990","iccid错误，没有查询到此流量卡");
		}
		String areaId = card.getAreaId();//卡所属地区
		String phonenumber = card.getPhonenumber();//卡所属地区
		if(StringUtils.isBlank(areaId)){
			throw new BizException("9990","此卡所属地区不明确，查询失败");
		}
		CardAmount cardAmount = cardAmountService.selectCardAmountByIccid(iccid);
		if(cardAmount == null){
			CardAmount c = new CardAmount();
			c.setIccid(iccid);
			c.setCreateTime(new Date());
			cardAmountService.insert(c);
			CardAmount cardInfo = cardAmountService.selectCardAmountByIccid(iccid);
			cardInfo.setCardId(phonenumber);
			return RespResult.getInstance(RespCode.SUCCESS,cardInfo);
		}else{
			cardAmount.setCardId(phonenumber);
			return RespResult.getInstance(RespCode.SUCCESS,cardAmount);
		}
	}
	
	/**
	 * 根据iccid查询套餐信息
	 * @param iccid
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "mpos/getPackList")
	@ResponseBody
	public RespResult getPackList(@RequestParam(value = "iccid", required = false)String iccid
			,HttpServletRequest request) {
		List<Package> list = WLWKService.packList(iccid);
		return RespResult.getInstance(RespCode.SUCCESS,list);
	}
	
	/**
	 * 生成支付宝预充值订单二维码
	 * @param iccid
	 * @param price
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "mpos/insertOrder")
	@ResponseBody
	public RespResult insertOrder(@RequestParam(value = "iccid", required = false)String iccid,
			@RequestParam(value = "money", required = false)Double money,
			@RequestParam(value = "pack_id", required = false)Integer packId,
			@RequestParam(value = "flow_type", required = false)int flowType,
			HttpServletRequest request) {
		Map<String,Object> map = WLWKService.insertOrder(iccid, money,packId,flowType);
		return RespResult.getInstance(RespCode.SUCCESS,map);
	}
	
	/**
	 * 使用余额充值流量卡
	 * @param iccid iccid卡号
	 * @param pkgId  套餐id
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "mpos/accountInsertOrder")
	@ResponseBody
	public RespResult accountInsertOrder(@RequestParam(value = "iccid", required = false)String iccid,
			@RequestParam(value = "pack_id", required = false)Integer pkgId,
			HttpServletRequest request) {
		WLWKService.accountInsertOrder(iccid,pkgId);
		return RespResult.getInstance(RespCode.SUCCESS);
	}
	
	/**
	 * 根据类型和iccid查询充值记录
	 * @param iccid
	 * @param type
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "mpos/rechargeRecordList")
	@ResponseBody
	public RespResult rechargeRecordList(@RequestParam(value = "iccid", required = false)String iccid,
			@RequestParam(value = "type", required = false)Integer type,
			HttpServletRequest request) {
		List<CardRechargeFlow> list = WLWKService.rechargeRecordList(iccid,type);
		return RespResult.getInstance(RespCode.SUCCESS,list);
	}
	
	/**
	 * 查询支付宝订单状态
	 * @param order_id
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "mpos/pollingOrder")
	@ResponseBody
	public RespResult pollingOrder(@RequestParam(value = "order_id", required = false)String orderId,
			HttpServletRequest request) {
		String  state = WLWKService.pollingOrder(orderId);
		return RespResult.getInstance(RespCode.SUCCESS,state);
	}
	
	/**
	 * 改变支付宝状态
	 * @param iccid
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "mpos/updateByIccid")
	@ResponseBody
	public RespResult updateByIccid(@RequestParam(value = "iccid", required = false)String iccid,
			@RequestParam(value = "autoTopUp", required = false)Integer autoTopUp,
			HttpServletRequest request) {
		WLWKService.updateByIccid(iccid,autoTopUp);
		return RespResult.getInstance(RespCode.SUCCESS);
	}
	
}